package com.cc.core;

import java.lang.reflect.Constructor;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cc.common.ContextUtil;



/**
 * SpringContextHelper 初始化监听类
 * 
 * @author kxm
 *
 */
public class InitSpringContextHelperListener implements ServletContextListener {
	private Logger logger =LoggerFactory.getLogger("[SpringContextHelper]");

	@Override
	public void contextDestroyed(ServletContextEvent sc) {}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Class<SpringContextHelper> clazz =SpringContextHelper.class;
		try {
			// 获取SpringContextHelper构造对象
			Constructor<SpringContextHelper> c =clazz.getDeclaredConstructor(ServletContext.class);
			// 设置有权访问
			c.setAccessible(true);
			// 直接创建一个SpringContextHelper对象， 此时SpringContexHelper会进行初始化
			c.newInstance(sce.getServletContext());
			initContextUtil(sce.getServletContext());
			logger.info("初始化完毕！");
		} catch (Exception e) {
			logger.error("初始化失败！", e);
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 
	 * 功能说明：将spring容器中所有的对象都放到ContextUtil中
	 *
	 * @param context context
	 * @throws Exception 获取ApplicationContext出错
	 *
	 */
	private void initContextUtil(ServletContext context) throws Exception {
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		ContextUtil.setContext(ctx);

	}

}
